const http = require("../../../utils/http");

Page({
  data: {
    username: '',
    adImages: []
  },

  onLoad: function () {
    const userInfo = wx.getStorageSync('userInfo');
    const username = userInfo?.userName || '';
    let imgList;
    if (userInfo?.indexImage) {
      // 将逗号分隔的字符串转为数组
      imgList = userInfo.indexImage.split(','); // 以逗号分隔成数组
    }
    this.setData({
      username,
      adImages: imgList
    });
  },

  // 页面跳转
  room() {
    wx.navigateTo({ url: '/pages/User/RoomHome/RoomHome' });
  },

  course() {
    wx.navigateTo({ url: '/pages/User/Course/Course' });
  },

  // 上传首页背景
  chooseAdImages() {
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        const userId = wx.getStorageSync('userInfo').id;

        const uploadPromises = tempFilePaths.map((filePath) => {
          return new Promise((resolve, reject) => {
            wx.uploadFile({
              url: 'http://127.0.0.1:8086/indexImage/upload', // 仅上传图片
              filePath: filePath,
              name: 'file',
              formData: { userId },
              success: (uploadRes) => {
                try {
                  const result = JSON.parse(uploadRes.data);
                  if (result.success) {
                    resolve(result.imagePath); // 单个路径
                  } else {
                    reject(result.message || '上传失败');
                  }
                } catch (e) {
                  reject('JSON 解析失败');
                }
              },
              fail: () => reject('上传失败')
            });
          });
        });

        Promise.all(uploadPromises).then((imagePaths) => {
          const pathStr = imagePaths.join(','); // 拼接成字符串
          // 更新数据库
          wx.request({
            url: 'http://127.0.0.1:8086/indexImage/save',
            method: 'POST',
            data: {
              userId,
              imagePaths: pathStr
            },
            success: (res) => {
              if (res.data.success) {
                const updatedList = imagePaths;
                const userInfo = wx.getStorageSync('userInfo');
                userInfo.indexImage = JSON.stringify(updatedList);
                wx.setStorageSync('userInfo', userInfo);

                this.setData({
                  adImages: updatedList
                });

                wx.showToast({
                  title: '上传成功',
                  icon: 'success'
                });
              } else {
                wx.showToast({
                  title: res.data.message || '保存失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络错误',
                icon: 'none'
              });
            }
          });
        }).catch((err) => {
          console.error('上传失败：', err);
          wx.showToast({
            title: '部分上传失败',
            icon: 'none'
          });
        });
      }
    });
  }
});